# app/models/init_locations.py
from sqlalchemy.orm import sessionmaker

from app.models.init_db import init_db
from app.map_planner.models import Warehouse1, Warehouse2

from app.map_planner.mapper import MapBase

def init_locations():
    """初始化库位数据，生成两套库位列表(LocationList1, LocationList2)。
    
    !!!! 注意：该初始化库位函数仅供参考，实际已弃用，请勿调用 !!!!

    该函数初始化的坐标不带库区号，格式如，'1,1' <-> '层,列'。
    """
    map_base = MapBase()
    map_list = map_base.locset_to_locstr(map_base.coordinates)
    ban_list = ["1,1", "2,1", "1,28", "2,28"]

    engine = init_db()
    Session = sessionmaker(bind=engine)
    session = Session()

    # 清空现有数据
    session.query(Warehouse1).delete()
    session.query(Warehouse2).delete()

    # 生成数据
    locations = list()
    for idx, loc in enumerate(map_list):
        if loc in ban_list:
            status = 8
        else:
            status = 0
        
        locations.append(Warehouse1(
            id=idx, 
            location=loc,
            pallet_id=None,
            status=status
        ))

        locations.append(Warehouse2(
            id=idx, 
            location=loc,
            pallet_id=None,
            status=status
        ))

    # 批量插入数据
    session.add_all(locations)
    session.commit()
    print(f"成功初始化{len(locations)}个库位数据")

def init_warehouse():
    """初始化库位数据，生成两套库位列表(Warehouse1, Warehouse2)。"""
    map_base = MapBase()
    wh_1_map_list = map_base.locstr_for_db(
        warehouse_id=1,
        loc_tuples=map_base.coordinates
        )
    wh_2_map_list = map_base.locstr_for_db(
        warehouse_id=2,
        loc_tuples=map_base.coordinates
        )
    ban_list = [
        "1,1,1", "1,2,1", "1,1,28", "1,2,28",
        "2,1,1", "2,2,1", "2,1,28", "2,2,28"
    ]

    engine = init_db()
    Session = sessionmaker(bind=engine)
    session = Session()

    # 清空现有数据
    session.query(Warehouse1).delete()
    session.query(Warehouse2).delete()

    # 生成数据
    locations = list()
    for idx, loc in enumerate(wh_1_map_list):
        if loc in ban_list:
            status = -1
        else:
            status = 0
        
        locations.append(Warehouse1(
            id=idx, 
            location=loc,
            pallet_id=None,
            status=status
        ))

    for idx, loc in enumerate(wh_2_map_list):
        if loc in ban_list:
            status = -1
        else:
            status = 0
        
        locations.append(Warehouse2(
            id=idx, 
            location=loc,
            pallet_id=None,
            status=status
        ))

    # 批量插入数据
    session.add_all(locations)
    session.commit()
    print(f"成功初始化{len(locations)}个库位数据")